package service

import (
	"gorm.io/gorm"
	"shop-bean/model"
	"shop-common/library/loggerV2"
	"shop-common/library/variables"
	"shop-common/utils/pagehelper"
	"shop-common/utils/queryWrapper"
	"shop-service/repository"
)

type IUserService interface {
	Page(request *pagehelper.SearchPageRequest) (*pagehelper.Record, error)
	FindById(userId string) (*model.User, error)
}

func NewUserService(repository repository.IUserRepository) IUserService {
	return &UserService{variables.GormDB(), repository}
}

type UserService struct {
	db         *gorm.DB
	repository repository.IUserRepository
}

func (s *UserService) Page(request *pagehelper.SearchPageRequest) (*pagehelper.Record, error) {
	paginator := pagehelper.New().SetOffset(request).
		IsPush(request.Keyword != "", queryWrapper.Like("nick_name", request.Keyword)).
		IsPush(request.Status > 0, queryWrapper.Eq("status", request.Status)).Paginator()

	count, err := s.repository.Count(s.db, paginator.Params)
	if err != nil {
		loggerV2.Errorf("find user to count failed: err %v, params %+v", err, paginator.Params)
		return paginator.Record, err
	}
	page, err := s.repository.FindPage(s.db, paginator.Params)
	if err != nil {
		loggerV2.Errorf("find user to page: err: %v, params %+v", err, paginator.Params)
		return paginator.Record, err
	}

	return paginator.Result(page, count)
}

func (s *UserService) FindById(userId string) (*model.User, error) {
	user, err := s.repository.FindById(s.db, userId)
	if err != nil {
		loggerV2.Errorf("findById to user failed: err %v, userId %d", err, userId)
		return nil, err
	}
	return user, nil
}
